package com.luoxiang.socialandroid.dialog

import android.content.Context
import android.view.LayoutInflater
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import com.luoxiang.lib_common.bean.NumberBean
import com.luoxiang.lib_common.common.Constants.MmkvConst.DOMAIN
import com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA
import com.luoxiang.lib_common.common.Constants.MmkvConst.KEY
import com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN
import com.luoxiang.lib_common.utils.MmkvUtil
import com.luoxiang.socialandroid.R
import com.luoxiang.socialandroid.adapter.Popupwindow2Adapter
import com.luoxiang.socialandroid.app.MyAppliaction
import com.luoxiang.socialandroid.bean.RandomOnlineBean
import com.luoxiang.socialandroid.bean.UserCallBean
import com.luoxiang.socialandroid.databinding.DialogBatchgreetingBinding
import com.luoxiang.socialandroid.utils.AESUtil
import com.luoxiang.socialandroid.utils.CustomClickListener
import com.luoxiang.socialandroid.utils.CustomClickListener2
import com.luoxiang.socialandroid.utils.MmkvUtil.encode
import com.luoxiang.socialandroid.utils.NetUtils
import com.lxj.xpopup.impl.FullScreenPopupView
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

class BatchGreetingDialog(context: Context) : FullScreenPopupView(context) {
    private lateinit var mViewBinding: DialogBatchgreetingBinding
    override fun getImplLayoutId() = R.layout.dialog_batchgreeting
    private var onCancleClickListener: (() -> Unit)? = null
    private var onTrueClickListener: (() -> Unit)? = null
    private var popupWindow: PopupWindow? = null
    private var flag = 0
    private var adapterpopp: Popupwindow2Adapter? = null
    private var recyclerView: RecyclerView? = null
    private var zhaohuid = 0
    private val list: ArrayList<Int> = ArrayList()
    private var userId1 = -1
    private var userId2 = -1
    private var userId3 = -1
    private var userId4 = -1
    private var userId5 = -1
    private var userId = -1
    override fun onCreate() {
        super.onCreate()
        mViewBinding = DialogBatchgreetingBinding.bind(popupImplView)
        getonlineMatchingList()
        getselectUserCallCentent()
        onClick()
        mViewBinding.imageView8.setOnClickListener {
            onCancleClickListener?.invoke()
        }
    }

    fun onClick() {
        mViewBinding.imageView15.setOnClickListener(object : CustomClickListener() {
            override fun onSingleClick() {
                getonlineMatchingList()
                if (list != null) {
                    list.clear()
                }
            }

            override fun onFastClick() {

            }

        })
        val view1 = LayoutInflater.from(context).inflate(R.layout.popover_view, null, false)
        popupWindow = PopupWindow(
            view1,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            true
        )
        popupWindow?.let {
            if (it.isFocusable()) {
                flag = 1
            }
            //消失监听听
            //消失监听听
            it.setOnDismissListener(PopupWindow.OnDismissListener {
                flag = if (it != null && it!!.isShowing) {
                    mViewBinding.iconTotop.setImageResource(R.mipmap.icon_totop)
                    1
                } else {
                    mViewBinding.iconTotop.setImageResource(R.mipmap.icon_tobottom)
                    0 //设置PopupWindow的显示位置，这里的参数分别是，参照View，X轴的偏移量，Y轴的偏移量
                }
            })
            recyclerView = it.contentView.findViewById(R.id.rv_popup)
        }
        mViewBinding.relaPopup.setOnClickListener(OnClickListener {
            popupWindow?.let {
                if (flag == 1) {
                    mViewBinding.iconTotop.setImageResource(R.mipmap.icon_tobottom)
                    flag = 0
                    it.dismiss()
                } else {
                    popupWindow!!.isShowing
                    mViewBinding.iconTotop.setImageResource(R.mipmap.icon_totop)
                    flag = 1 //设置PopupWindow的显示位置，这里的参数分别是，参照View，X轴的偏移量，Y轴的偏移量
                    it.showAsDropDown(mViewBinding.relaPopup, 50, 0)
                    getselectUserCallCentent()

                }
            }

        })
        mViewBinding.textView22.setOnClickListener(object : CustomClickListener2() {
            override fun onSingleClick() {
                //单点一键打招呼
                if (userId != null && userId != -1) {
                    list.add(userId)
                }
                if (userId1 != null && userId1 != -1) {
                    list.add(userId1)
                }
                if (userId2 != null && userId2 != -1) {
                    list.add(userId2)
                }
                if (userId3 != null && userId3 != -1) {
                    list.add(userId3)
                }
                if (userId4 != null && userId4 != -1) {
                    list.add(userId4)
                }
                if (userId5 != null && userId5 != -1) {
                    list.add(userId5)
                }
                getsayHelloBatch(zhaohuid)


            }

            override fun onFastClick() {
                ToastUtils.showShort("当前点击速度过快。")
            }

        })


    }

    fun setOnCancleClickListener(onCancleClickListener: () -> Unit) {
        this.onCancleClickListener = onCancleClickListener
    }

    fun setOnTrueClickListener(onTrueClickListener: () -> Unit) {
        this.onTrueClickListener = onTrueClickListener
    }

    /**
     * 请求随机获取在线用户
     */
    fun getonlineMatchingList() {
        NetUtils.getInstance().apiService.getonlineMatchingList(
            EXTRA,
            MmkvUtil.decodeString(TOKEN),
            10
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean?> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(numberBean: NumberBean?) {
                    val data: String? = numberBean?.getData()
                    var decryptStr: String? = null
                    try {
                        decryptStr = AESUtil.aesDecryptString(data, KEY)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    LogUtils.i("decryptStr900", decryptStr)
                    val gson = Gson()
                    val randomonlinebean = gson.fromJson(
                        decryptStr,
                        RandomOnlineBean::class.java
                    )
                    if (randomonlinebean.data!=null){
                        if (randomonlinebean.data.users!=null){
                if (!randomonlinebean.data.users.isEmpty()) {
                    if (randomonlinebean.data.users.size >0) {
                        val icon1 = randomonlinebean.data.users[0].icon
                        val name1 = randomonlinebean.data.users[0].name
                        userId = randomonlinebean.data.users[0].userId
                        Glide.with(MyAppliaction.getContext())
                            .load(DOMAIN + icon1)
                            .apply(RequestOptions.bitmapTransform(CircleCrop())) //设置圆形头像
                            .into(mViewBinding.imageView9)
                        mViewBinding.textView20.text = name1
                        if (randomonlinebean.data.users.size>1){
                            val name2 = randomonlinebean.data.users[1].name
                            val icon2 = randomonlinebean.data.users[1].icon
                            Glide.with(MyAppliaction.getContext())
                                .load(DOMAIN + icon2)
                                .apply(RequestOptions.bitmapTransform(CircleCrop())) //设置圆形头像
                                .into(mViewBinding.imageView10)
                            mViewBinding.textView17.text = name2
                            userId1 = randomonlinebean.data.users[1].userId
                        }

                    }
                    if (randomonlinebean.data.users.size > 2) {
                        val name3 = randomonlinebean.data.users[2].name
                        val icon3 = randomonlinebean.data.users[2].icon
                        Glide.with(MyAppliaction.getContext())
                            .load(DOMAIN + icon3)
                            .apply(RequestOptions.bitmapTransform(CircleCrop())) //设置圆形头像
                            .into(mViewBinding.imageView11)
                        mViewBinding.textView19.text = name3
                        userId2 = randomonlinebean.data.users[2].userId

                    }
                    if (randomonlinebean.data.users.size > 3) {
                        val name4 = randomonlinebean.data.users[3].name
                        val icon4 = randomonlinebean.data.users[3].icon
                        Glide.with(MyAppliaction.getContext())
                            .load(DOMAIN + icon4)
                            .apply(RequestOptions.bitmapTransform(CircleCrop())) //设置圆形头像
                            .into(mViewBinding.imageView12)
                        mViewBinding.textView18.text = name4
                        userId3 = randomonlinebean.data.users[3].userId

                    }

                    if (randomonlinebean.data.users.size > 4) {
                        val name5 = randomonlinebean.data.users[4].name
                        val icon5 = randomonlinebean.data.users[4].icon
                        Glide.with(MyAppliaction.getContext())
                            .load(DOMAIN + icon5)
                            .apply(RequestOptions.bitmapTransform(CircleCrop())) //设置圆形头像
                            .into(mViewBinding.imageView13)
                        mViewBinding.textView21.text = name5
                        userId4 = randomonlinebean.data.users[4].userId

                    }
                    if (randomonlinebean.data.users.size > 5) {
                        val icon6 = randomonlinebean.data.users[5].icon
                        val name6 = randomonlinebean.data.users[5].name
                        Glide.with(MyAppliaction.getContext())
                            .load(DOMAIN + icon6)
                            .apply(RequestOptions.bitmapTransform(CircleCrop())) //设置圆形头像
                            .into(mViewBinding.imageView14)
                        mViewBinding.name6.text = name6
                        userId5 = randomonlinebean.data.users[5].userId

                    }
                }
            }
    }




}

override fun onError(e: Throwable) {}
override fun onComplete() {}


})
    }

    /**
     * 请求获取用户招呼语列表
     */
    fun getselectUserCallCentent() {
        NetUtils.getInstance().apiService.getselectUserCallCentent(
            EXTRA,
            MmkvUtil.decodeString(TOKEN)
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                val data: String? = it?.getData()
                var decryptStr: String? = null
                try {
                    decryptStr = AESUtil.aesDecryptString(data, KEY)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                LogUtils.i("decryptStr1000", decryptStr)
                val gson = Gson()
                val userCallBean = gson.fromJson(
                    decryptStr,
                    UserCallBean::class.java
                )
                if (userCallBean.code != 0) {
                    userCallBean.msg
                    return@subscribe
                }
                userCallBean.data.hostCallContents.let {
                    adapterpopp = Popupwindow2Adapter(it)
                    val linearLayoutManager = LinearLayoutManager(context)
                    recyclerView?.let {
                        it.layoutManager = linearLayoutManager
                        it.adapter = adapterpopp
                    }
                    adapterpopp!!.setOnAddClickListener { id, content ->
                        mViewBinding.tvZhaohuyu.text = content
                        zhaohuid = id
                    }


                }
                if (userCallBean.data.hostCallContents.size > 1) {
                    val content = userCallBean.data.hostCallContents[0].content
                    mViewBinding.tvZhaohuyu.text = content
                    zhaohuid = userCallBean.data.hostCallContents[0].id
                }


            }
    }

    /**
     *批量打招呼接口
     */
    fun getsayHelloBatch(contentId: Int) {
        NetUtils.getInstance().apiService.getsayHelloBatch(
            EXTRA,
            MmkvUtil.decodeString(TOKEN),
            list,
            contentId
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                val data: String? = it?.getData()
                var decryptStr: String? = null
                try {
                    decryptStr = AESUtil.aesDecryptString(data, KEY)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                LogUtils.i("decryptStrpiliang", decryptStr)
                val gson = Gson()
                val userCallBean = gson.fromJson(
                    decryptStr,
                    UserCallBean::class.java
                )
                if (userCallBean.code != 0) {
                    ToastUtils.showShort(userCallBean.msg)
                } else {
                    onTrueClickListener?.invoke()
                    ToastUtils.showShort(context.getString(R.string.mi_dazhaohuchenggong))
                    encode("isshowdialogbatch", "")

                }

            }
    }


}